import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Typography, Modal, Spin, Alert, message } from 'antd';
import { 
  FileOutlined, 
  EyeOutlined, 
  DownloadOutlined, 
  FullscreenOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import './PdfViewer.scss';

const { Title, Text } = Typography;

const PdfViewer = ({ attachment, showActions = true }) => {
  const [fullscreenVisible, setFullscreenVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [pdfStatus, setPdfStatus] = useState(attachment.pdf_status || attachment.pdfStatus || 'unknown');
  const [pdfUrl, setPdfUrl] = useState(attachment.pdf_url || attachment.pdfUrl);
  const [checkingStatus, setCheckingStatus] = useState(false);

  // 检查PDF转换状态
  const checkPdfStatus = async () => {
    if (!attachment.id || pdfStatus === 'completed') return;
    
    try {
      setCheckingStatus(true);
      const response = await fetch(`http://211.86.197.10:9091/api/pdf-conversions/status/${attachment.id}`);
      const result = await response.json();
      
      if (result.success && result.data) {
        const newStatus = result.data.conversion_status;
        const newPdfUrl = result.data.pdf_url;
        
        setPdfStatus(newStatus);
        if (newPdfUrl && newPdfUrl !== pdfUrl) {
          setPdfUrl(newPdfUrl);
          message.success('PDF转换完成，现在可以预览了！');
        }
      }
    } catch (error) {
      console.error('检查PDF状态失败:', error);
    } finally {
      setCheckingStatus(false);
    }
  };

  // 定期检查PDF转换状态
  useEffect(() => {
    if (pdfStatus === 'processing' || pdfStatus === 'unknown') {
      const interval = setInterval(checkPdfStatus, 5000); // 每5秒检查一次
      return () => clearInterval(interval);
    }
  }, [pdfStatus, attachment.id]);

  const handleDownload = () => {
    const link = document.createElement('a');
    link.href = `http://211.86.197.10:9091${attachment.file_url}`;
    link.download = attachment.original_name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handlePdfPreview = () => {
    if (pdfUrl) {
      const fullPdfUrl = pdfUrl.startsWith('http') ? pdfUrl : `http://211.86.197.10:9091${pdfUrl}`;
      window.open(fullPdfUrl, '_blank');
    }
  };

  const handleFullscreen = () => {
    setFullscreenVisible(true);
  };

  const handleRefreshStatus = () => {
    checkPdfStatus();
  };

  const renderPdfEmbed = (height = '600px', isFullscreen = false) => {
    // 检查PDF是否可用
    if (!pdfUrl || pdfStatus === 'processing' || pdfStatus === 'unknown') {
      return (
        <Alert
          message="PDF预览不可用"
          description={
            <div>
              <p>该文档的PDF版本正在生成中，请稍后刷新页面或直接下载原文件查看。</p>
              {(pdfStatus === 'processing' || pdfStatus === 'unknown') && (
                <div style={{ marginTop: 12 }}>
                  <Button 
                    size="small" 
                    icon={<ReloadOutlined />} 
                    onClick={handleRefreshStatus}
                    loading={checkingStatus}
                  >
                    检查转换状态
                  </Button>
                </div>
              )}
            </div>
          }
          type="warning"
          showIcon
        />
      );
    }

    if (pdfStatus === 'failed') {
      return (
        <Alert
          message="PDF转换失败"
          description={
            <div>
              <p>文档转换为PDF时出现错误，请下载原文件查看。</p>
              <div style={{ marginTop: 12 }}>
                <Button 
                  size="small" 
                  icon={<ReloadOutlined />} 
                  onClick={handleRefreshStatus}
                  loading={checkingStatus}
                >
                  重新检查
                </Button>
              </div>
            </div>
          }
          type="error"
          showIcon
        />
      );
    }

    // 构建PDF URL，确保包含完整路径
    const fullPdfUrl = pdfUrl.startsWith('http') ? pdfUrl : `http://211.86.197.10:9091${pdfUrl}`;

    // 如果是占位符，显示特殊提示
    if (pdfStatus === 'placeholder') {
      return (
        <div className="pdf-embed-container">
          <Alert
            message="PDF占位符"
            description={
              <div>
                <p>系统已为此文档创建了PDF占位符，点击下方按钮查看详细信息。</p>
                <div style={{ marginTop: 12 }}>
                  <Button 
                    type="primary"
                    size="small" 
                    onClick={() => window.open(fullPdfUrl, '_blank')}
                  >
                    查看占位符页面
                  </Button>
                  <Button 
                    size="small" 
                    icon={<ReloadOutlined />} 
                    onClick={handleRefreshStatus}
                    loading={checkingStatus}
                    style={{ marginLeft: 8 }}
                  >
                    检查转换状态
                  </Button>
                </div>
              </div>
            }
            type="info"
            showIcon
          />
        </div>
      );
    }

    const containerStyle = isFullscreen ? {
      flex: 1,
      display: 'flex',
      flexDirection: 'column',
      minHeight: 0
    } : {
      position: 'relative'
    };

    const iframeStyle = isFullscreen ? {
      flex: 1,
      width: '100%',
      border: '1px solid #d9d9d9',
      borderRadius: '6px',
      backgroundColor: '#fff'
    } : {
      border: '1px solid #d9d9d9', 
      borderRadius: '6px',
      backgroundColor: '#fff'
    };

    return (
      <div className="pdf-embed-container" style={containerStyle}>
        <iframe
          src={fullPdfUrl}
          width="100%"
          height={isFullscreen ? undefined : height}
          style={iframeStyle}
          title={`PDF预览 - ${attachment.original_name}`}
          onLoad={() => setLoading(false)}
          onError={() => setLoading(false)}
        />
        {loading && (
          <div className="pdf-loading-overlay">
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>加载PDF中...</div>
          </div>
        )}
      </div>
    );
  };

  return (
    <Card className="pdf-viewer-card">
      {/* 文件信息头部 */}
      <div className="pdf-header">
        <Space>
          <FileOutlined style={{ fontSize: '24px', color: '#1890ff' }} />
          <div className="file-info">
            <Title level={5} style={{ margin: 0 }}>
              {attachment.original_name}
            </Title>
            <Text type="secondary">
              {(attachment.file_size / 1024 / 1024).toFixed(2)} MB
              {pdfStatus === 'completed' && ' • PDF可用'}
              {pdfStatus === 'processing' && ' • PDF生成中'}
              {pdfStatus === 'placeholder' && ' • PDF占位符'}
              {pdfStatus === 'failed' && ' • PDF生成失败'}
              {pdfStatus === 'unknown' && ' • 检查PDF状态中'}
            </Text>
          </div>
        </Space>
        
        {showActions && (
          <Space>
            {pdfUrl && pdfStatus === 'completed' && (
              <>
                <Button 
                  icon={<EyeOutlined />}
                  onClick={handlePdfPreview}
                >
                  新窗口预览
                </Button>
                <Button 
                  icon={<FullscreenOutlined />}
                  onClick={handleFullscreen}
                >
                  全屏预览
                </Button>
              </>
            )}
            {pdfUrl && pdfStatus === 'placeholder' && (
              <Button 
                icon={<EyeOutlined />}
                onClick={handlePdfPreview}
              >
                查看占位符
              </Button>
            )}
            {(pdfStatus === 'processing' || pdfStatus === 'unknown' || pdfStatus === 'failed') && (
              <Button 
                icon={<ReloadOutlined />}
                onClick={handleRefreshStatus}
                loading={checkingStatus}
              >
                检查状态
              </Button>
            )}
            <Button 
              icon={<DownloadOutlined />}
              onClick={handleDownload}
            >
              下载原文件
            </Button>
          </Space>
        )}
      </div>

      {/* PDF内嵌预览 */}
      <div className="pdf-content">
        {renderPdfEmbed()}
      </div>

      {/* 全屏预览模态框 */}
      <Modal
        title={`PDF预览 - ${attachment.original_name}`}
        open={fullscreenVisible}
        onCancel={() => setFullscreenVisible(false)}
        footer={null}
        width="98vw"
        style={{ top: 10, maxWidth: 'none' }}
        className="pdf-fullscreen-modal"
        centered={false}
        closable={true}
        maskClosable={false}
      >
        <div className="pdf-fullscreen-content">
          {renderPdfEmbed(undefined, true)}
        </div>
      </Modal>
    </Card>
  );
};

export default PdfViewer;